<script setup lang='ts'>
import { ref, onMounted, onUnmounted} from 'vue'
import UtilsBox from '@/components/UtilsBox/index.vue'
import { debounce, throttle, formatDate, formatFileSize, formatTimeSize } from '@/utils/common'

// 防抖节流
const num = ref(0)
const debounceClick = debounce(()=>{
  num.value++
},1000)

const throttleClick = throttle(()=>{
  num.value++
},1000)

// 时间格式化
const currentTime = ref(formatDate(new Date(), 'YYYY-MM-DD hh:mm:ss'))
let timer: number | null = null

onMounted(() => {
  timer = window.setInterval(() => { // 每秒更新一次时间
    currentTime.value = formatDate(new Date(), 'YYYY-MM-DD hh:mm:ss')
  }, 1000)
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer) // 组件卸载时清除定时器
  }
})

// 文件单位格式化
const fileSize = ref<number | null>(null)
const fileSizeResult = ref<string | null>(null)
const submitFileSize = () => {
  if (fileSize.value) {
    fileSizeResult.value = formatFileSize(Number(fileSize.value))
  }
}

// 时长格式化
const time = ref<number | null>(null)
const timeResult = ref<string | null>(null)
const submitTime = () => {
  if (time.value) {
    timeResult.value = formatTimeSize(Number(time.value))
  }
}

</script>


<template>
  <div class="container">
    <UtilsBox title="防抖">
      <div>定义：在事件被触发n秒后再执行回调，如果在这n秒内又被触发，则重新计时</div>
      <div>场景：搜索框输入，按钮点击</div>
      <hr class="hr">
      <el-button type="warning" plain @click="debounceClick">按钮</el-button>
      <div>num: {{ num }}</div>
      <span>点击按钮1s后num++</span>
    </UtilsBox>
    <UtilsBox title="节流">
      <div>定义：在事件被触发n秒后再执行回调，如果在这n秒内又被触发，则不执行</div>
      <div>场景：滚动，窗口大小改变，鼠标移动</div>
      <hr class="hr">
      <el-button type="warning" plain @click="throttleClick">按钮</el-button>
      <div>num: {{ num }}</div>
      <span>点击按钮每1s num++一次</span>
    </UtilsBox>
    <UtilsBox title="时间格式化">
      <div>定义：将时间戳格式化为指定格式</div>
      <div>场景：时间显示</div>
      <hr class="hr">
      <div>当前时间：<br/>{{ currentTime }}</div>
    </UtilsBox>
    <UtilsBox title="文件单位格式化">
      <div>定义：将文件单位优化为最佳格式</div>
      <div>场景：上传文件后文件大小展示</div>
      <hr class="hr">
      <el-input v-model="fileSize" placeholder="请输入文件大小,单位为字节(B)" clearable style="margin-bottom: 10px;"></el-input>
      <el-button type="warning" plain style="margin-bottom: 10px;" @click="submitFileSize">提交</el-button>
      <div>文件大小: {{ fileSizeResult }}</div>
    </UtilsBox>
    <UtilsBox title="时长格式化">
      <div>定义：将时长优化为最佳格式</div>
      <div>场景：累计物品使用时长/租出时长/阅读时长等</div>
      <hr class="hr">
      <el-input v-model="time" placeholder="请输入时长,单位为秒(s)" clearable style="margin-bottom: 10px;"></el-input>
      <el-button type="warning" plain style="margin-bottom: 10px;" @click="submitTime">提交</el-button>
      <div>时长: {{ timeResult }}</div>
    </UtilsBox>

  </div>
</template>


<style scoped lang="scss">
  .container {
    padding: 20px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-evenly;
    color: #AB675C;
    font-size: 14px;
  }
  .hr{
    margin: 10px 0;
  }
</style>